/*****************************************************************************************
**  Author:dgz master
**  Contact：jiduxiong@dagongzao.com
**
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import axios from 'axios';

let extension = {
  // 添加全局变量存储累加值
  globalData: {
    // 注意：这里移除了重复定义的totalDefectBlankQty
    totalDefectGrindingQty: 0,          // 磨加工不良累加
    totalDefectPunchingQty: 0,          // 打掏孔不良累加
    totalDefectLinearQty: 0,            // 线切割不良累加
    totalDefectCuteQty: 0,              // 切方不良累加
    totalDefectVariableQty: 0,          // 异形磨不良累加
    totalDefectFringeQty: 0,            // 平磨不良累加
    totalDefectSliceQty: 0,             // 切片不良累加
    totalDefectChamferQty: 0,           // 倒角不良累加
    totalDefectPlatingQty: 0,           // 电镀不良累加
    totalReworkDefectQty: 0,            // 电镀可返不良累加
    totalChipFinalQty: 0,               // 电镀检出崩边累加
    totalDefectBlackFinalQty: 0,        // 电镀检出黑磕累加
    totalPlatingCheckFallQty: 0,        // 检包落地片累加
    totalMagnetizationFallQty: 0,       // 充磁不良累加
    totalSamplingReliabilityQty: 0,     // 送测样品累加

    // 毛坯相关累加
    totalDefectBlankQty: 0,             // 毛坯不良累加（修正重复定义问题）
    totalMaterialEbQty: 0,              // 毛坯磕边累加
    totalMaterialCrackQty: 0,           // 毛坯裂纹累加
    totalMaterialDitQty: 0,             // 毛坯砂眼累加
    totalMaterialLightspotQty: 0,       // 毛坯亮点累加
    totalMaterialSiliconeOilQty: 0,     // 毛坯硅油累加
    totalMaterialFluxBadQty: 0,         // 毛坯磁通不良累加
    totalMaterialOxygenQty: 0,          // 毛坯氧化累加
    totalMaterialMiscQty: 0,            // 黑皮/退料累加

    // 磨加工相关累加
    totalDefectGrindingEbQty: 0,        // 磨加工磕边累加
    totalDefectGrindingProcessQty: 0,   // 磨加工工残累加

    // 打掏孔相关累加
    totalDefectPunchingEbQty: 0,        // 打掏孔磕边累加
    totalDefectPunchingProcessQty: 0,   // 打掏孔工残累加

    // 平磨相关累加
    totalDefectFringeEbQty: 0,          // 平磨磕边累加
    totalDefectFringeProcessQty: 0,     // 平磨工残累加

    // 线切割相关累加
    totalDefectLinearEbQty: 0,          // 线切割磕边累加
    totalDefectLinearProcessQty: 0,     // 线切割工残累加

    // 切方相关累加
    totalDefectCuteEbQty: 0,            // 切方磕边累加
    totalDefectCuteProcessQty: 0,       // 切方工残累加

    // 异形磨相关累加
    totalDefectVariableEbQty: 0,        // 异形磨磕边累加
    totalDefectVariableProcessQty: 0,   // 异形磨工残累加
    totalDefectVariableVerticalityQty: 0,// 异形磨垂直度超差累加
    totalDefectVariablePitQty: 0,       // 异形磨麻坑累加

    // 切片相关累加
    totalDefectSliceEbQty: 0,           // 切片磕边累加
    totalDefectSliceProcessQty: 0,      // 切片工残累加
    totalDefectSliceMarkQty: 0,         // 切片刀痕累加
    totalDefectSliceVerticalityQty: 0,  // 切片垂直度超差累加
    totalDefectSliceSizeQty: 0,         // 切片尺寸超差累加
    totalDefectSlicePitQty: 0,          // 切片麻坑累加

    // 倒角相关累加
    totalDefectChamferEbQty: 0,         // 倒角磕边累加
    totalDefectChamferProcessQty: 0,    // 倒角工残累加
    totalDefectChamferPitQty: 0,        // 倒角麻坑累加

    // 电镀相关累加
    totalDefectPlatingConcavePitQty: 0, // 电镀凹坑累加
    totalDefectPlatingColordiffQty: 0,  // 电镀镀层色差累加
    totalDefectPlatingSizeQty: 0,       // 电镀尺寸超差累加
    totalDefectPlatingFluxQty: 0,       // 电镀结合力不良累加
    totalDefectPlatingEdgeBrokenQty: 0, // 电镀磕边累加
    totalDefectPlatingPaintQty: 0,      // 喷涂集漆累加
    totalDefectPlatingNetQty: 0,        // 喷涂粘网累加
    totalDefectPlatingForeignQty: 0,    // 喷涂异物累加
    totalDefectPlatingBubbleQty: 0,     // 电镀气泡累加
    totalDefectPlatingPitQty: 0,        // 电镀麻坑累加
    totalDefectPlatingDisabilityQty: 0, // 电镀镀残累加

    // 可返相关累加
    totalReworkTestQty: 0,              // 可返实验累加
    totalReworkColordiffQty: 0,         // 可返镀层色差累加
    totalReworkScratchQty: 0,           // 可返镀层划痕累加
    totalReworkBlisterQty: 0,           // 可返起泡累加
    totalReworkOutoftolQty: 0,          // 可返超差累加
    totalReworkEdgeBrokenQty: 0,        // 可返磕边累加
    totalReworkPitQty: 0,               // 可返凹坑累加
    totalReworkPaintQty: 0,             // 可返集漆累加
    totalReworkForeignQty: 0,           // 可返异物累加
    totalReworkNetQty: 0,               // 可返粘网累加
    totalReworkPlatingPaintQty: 0       // 可返电镀掉漆累加
  },

  components: {
    //查询界面扩展组件
    gridHeader: "",
    gridBody: "",
    gridFooter: "",
    //新建、编辑弹出框扩展组件
    modelHeader: "",
    modelBody: "",
    modelRight: "",
    modelFooter: ""
  },

  tableAction: "", //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    onInit() {
      // 定义所有需要同步的字段配置
      const syncFields = [
        // 基础不良类型
        "DefectBlankQty", "DefectGrindingQty", "DefectPunchingQty",
        "DefectLinearQty", "DefectCuteQty", "DefectVariableQty",
        "DefectFringeQty", "DefectSliceQty", "DefectChamferQty",
        "DefectPlatingQty", "ReworkDefectQty", "ChipFinalQty",
        "DefectBlackFinalQty", "PlatingCheckFallQty", "MagnetizationFallQty",
        "SamplingReliabilityQty",

        // 毛坯相关
        "MaterialEbQty", "MaterialCrackQty", "MaterialDitQty",
        "MaterialLightspotQty", "MaterialSiliconeOilQty", "MaterialFluxBadQty",
        "MaterialOxygenQty", "MaterialMiscQty",

        // 磨加工相关
        "DefectGrindingEbQty", "DefectGrindingProcessQty",

        // 打掏孔相关
        "DefectPunchingEbQty", "DefectPunchingProcessQty",

        // 平磨相关
        "DefectFringeEbQty", "DefectFringeProcessQty",

        // 线切割相关
        "DefectLinearEbQty", "DefectLinearProcessQty",

        // 切方相关
        "DefectCuteEbQty", "DefectCuteProcessQty",

        // 异形磨相关
        "DefectVariableEbQty", "DefectVariableProcessQty",
        "DefectVariableVerticalityQty", "DefectVariablePitQty",

        // 切片相关
        "DefectSliceEbQty", "DefectSliceProcessQty", "DefectSliceMarkQty",
        "DefectSliceVerticalityQty", "DefectSliceSizeQty", "DefectSlicePitQty",

        // 倒角相关
        "DefectChamferEbQty", "DefectChamferProcessQty", "DefectChamferPitQty",

        // 电镀相关
        "DefectPlatingConcavePitQty", "DefectPlatingColordiffQty",
        "DefectPlatingSizeQty", "DefectPlatingFluxQty",
        "DefectPlatingEdgeBrokenQty", "DefectPlatingPaintQty",
        "DefectPlatingNetQty", "DefectPlatingForeignQty",
        "DefectPlatingBubbleQty", "DefectPlatingPitQty",
        "DefectPlatingDisabilityQty",

        // 可返相关
        "ReworkTestQty", "ReworkColordiffQty", "ReworkScratchQty",
        "ReworkBlisterQty", "ReworkOutoftolQty", "ReworkEdgeBrokenQty",
        "ReworkPitQty", "ReworkPaintQty", "ReworkForeignQty",
        "ReworkNetQty", "ReworkPlatingPaintQty"
      ];

      // 定义其他需要直接赋值的字段
      const assignFields = [
        "InpectionTime", "ProductId", "Grade", "Plating",
        "BlankLotName", "Spec", "AtmMonth", "ScheduleId",
        "OutgoingFinalQty", "IncomingQualifiedFinalQty"
      ];

      // 提取公共的同步处理函数
      const handleSync = (factoryField, waveIdField) => {
        // 确保全局数据对象存在
        if (!this.globalData) {
          this.globalData = {};
        }

        if (this.editFormFields?.[factoryField]?.trim() !== "") {
          const locationWaveId = {
            Location: String(this.editFormFields[factoryField] || ''),
            WaveId: String(this.editFormFields[waveIdField] || '')
          };

          const loadingInstance = this.$loading({
            lock: true,
            text: '同步MES数据中···',
            spinner: 'el-icon-loading',
            background: 'rgba(247, 237, 237, 0.7)'
          });

          // 根据不同场景选择不同的axios实例
          const axiosInstance = axios.create({ timeout: 6000000 });

          axiosInstance.post('api/Quality_Daily_Report/SyncQualityDailyReport', locationWaveId)
            .then((response) => {
              console.log(`同步成功${waveIdField === 'WaveId1' ? '1' : ''}:`, response);
              loadingInstance.close();

              // 接口返回数据通常在response.data中
              const result = response.data || [];
              // 确保result是数组且有数据
              const data = Array.isArray(result) && result.length > 0 ? result[0] : {};

              // 处理需要累加的字段
              syncFields.forEach(field => {
                const totalField = `total${field}`;
                // 初始化未定义的全局变量
                if (this.globalData[totalField] === undefined) {
                  this.globalData[totalField] = 0;
                }
                // 累加数据（确保数据是数字类型）
                this.globalData[totalField] += Number(data[field]) || 0;
                // 更新表单字段
                this.editFormFields[field] = this.globalData[totalField];
              });

              // 处理直接赋值的字段
              assignFields.forEach(field => {
                // 特殊处理OutgoingFinalQty，比如北方做毛坯，山东做电镀，谁的电镀不良数不为0，就取其合格数。（还未实现）
                if (field === 'OutgoingFinalQty') {
                  // 确保当前值和新值都是数字
                  const currentValue = Number(this.editFormFields[field]) || 0;
                  const newValue = Number(data[field]) || 0;
                  if (newValue > currentValue) {
                    this.editFormFields[field] = newValue;
                  }
                } else {
                  //只有当是主工厂时才改变其他文本框内容
                  if (waveIdField === 'WaveId1') {
                    this.editFormFields[field] = data[field];
                  }
                }
              });
            })
            .catch((error) => {
              console.error('同步失败:', error);
              loadingInstance.close();
              this.$message.error('同步失败，请稍后重试');
            });
        } else {
          this.$message.error('请选择主工厂');
        }
      };

      // 循环处理表单选项
      this.editFormOptions.forEach((option) => {
        option.forEach((item) => {
          // 根据不同的field配置不同的点击事件
          if (['WaveId1', 'WaveId2', 'WaveId3'].includes(item.field)) {
            const factoryField = `Factory${item.field.replace('WaveId', '')}`;

            item.extra = {
              render: (h) => (
                <div>
                  <el-button
                    type="primary"
                    link
                    onClick={() => handleSync(factoryField, item.field)}
                  >
                    <i class="el-icon-search">查询</i>
                  </el-button>
                </div>
              )
            };
          }
        });
      });
    },
    onInited() {
      // 初始化时确保globalData所有字段都有值
      if (!this.globalData) {
        this.globalData = {};
      }
    },
    //需要现在onInited()中先声明该方法
    initFormSelectTable(item) {
    },
    searchBefore(param) {
      return true;
    },
    searchAfter(result) {
      return true;
    },
    addBefore(formData) {
      return true;
    },
    updateBefore(formData) {
      return true;
    },
    delBefore(formData) {
      return true;
    },
    addAfter(formData) {
      return true;
    },
    updateAfter(formData) {
      return true;
    },
    delAfter(formData) {
      return true;
    },
    rowClick({ row, column, event }) {
    },
    modelOpenAfter(row) {
    }
  }
};
export default extension;
